package com.myworkspace.standard.common.utils;

import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 自定义工具类，常用功能封装处理
 */
public class CustomUtils {
    /**
     * 得到唯一UUID
     *
     * @return
     */
    public static String getGuid() {
        String uuid = UUID.randomUUID().toString();
        String id = uuid.replaceAll("-", "");
        return id;
    }

    /**
     * 根据KEY得到对应的配置文件值
     *
     * @param key
     * @return
     */
    public static String getPropertyBykey(String pfilename, String key, String defaultString) {
        ResourceBundle rb = ResourceBundle.getBundle(pfilename);
        String value = rb.getString(key) == null ? defaultString : rb.getString(key);
        return value;
    }

    /**
     * 判断某个字符串是否被包含字符数组中的元素
     *
     * @param str   要检测的字符串
     * @param array 字符串数组
     * @param model 模式（如果为1，刚只要包含数组中的某一个元素，则返回true,如果为2，则必需全部包含字符数组中的所有元素，才返回true，
     *              否则返回false）
     * @return
     */
    public static boolean stringContainsArray(String str, String[] array, int model) {
        boolean flag = false;
        int j = 0;
        for (String temp : array) {
            if (str.contains(temp)) {
                j++;
            }
        }
        if (model == 1) {
            if (j > 0) {
                flag = true;
            }
        }
        if (model == 2) {
            if (j == array.length) {
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 判断某个字符串是否等于字符数组中的元素
     *
     * @param str   要检测的字符串
     * @param array 字符串数组
     * @param model 模式（如果为1，刚只要包含数组中的某一个元素，则返回true,如果为2，则必需全部包含字符数组中的所有元素，才返回true，
     *              否则返回false）
     * @return
     */
    public static boolean stringInArray(String str, String[] array, int model) {
        boolean flag = false;
        int j = 0;
        for (String temp : array) {
            if (str.equals(temp)) {
                j++;
            }
        }
        if (model == 1) {
            if (j > 0) {
                flag = true;
            }
        }
        if (model == 2) {
            if (j == array.length) {
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 生成指定长度的随机字符串
     *
     * @param length 字符串长度
     * @return
     */
    public static String createNoncestr(int length) {
        String chars = "abcdefghjLkmnpqrstuvwxyz23456789";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int index = new Random().nextInt(32);
            String getChar = chars.substring(index, index + 1);
            sb.append(getChar);
        }
        return sb.toString();
    }

    /**
     * 生成指定长度的随机字符串
     *
     * @param length 字符串长度
     * @return
     */
    public static String createNoncestrToUpper(int length) {
        String chars = "abcdefghjLkmnpqrstuvwxyz23456789";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int index = new Random().nextInt(32);
            String getChar = chars.substring(index, index + 1);
            getChar = getChar.toUpperCase();
            sb.append(getChar);
        }
        return sb.toString();
    }

    /**
     * 生成指定长度的随机数字
     *
     * @param length
     * @return
     */
    public static String createNoncenum(int length) {
        String chars = "0123456789";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int index = new Random().nextInt(10);
            sb.append(chars.substring(index, index + 1));
        }
        return sb.toString();
    }

    /**
     * 将base64字符串解码为UTF-8字符串
     *
     * @param s
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String Base64DecodeToUtf8(String s)
            throws UnsupportedEncodingException {

        return new String(Base64.getDecoder().decode(s), "UTF-8");
    }

    /**
     * 将字符串编码为UTF8格式base64字符串
     *
     * @param s
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String Base65EncodeToUtf8(String s)
            throws UnsupportedEncodingException {
        return new String(Base64.getEncoder().encode(s.getBytes("UTF-8")));
    }

    /**
     * 字符编码转换，主要用于文件下载中设置下载文件名称
     *
     * @param fileName
     * @return
     */
    public static String convertFileNameEncoding(String fileName) {
        String returnFileName = "";
        try {
            returnFileName = URLEncoder.encode(fileName, "UTF-8");
            returnFileName = StringUtils.replace(returnFileName, "+", "%20");
            if (returnFileName.length() > 150) {
                returnFileName = new String(fileName.getBytes("GB2312"),
                        "ISO8859-1");
                returnFileName = StringUtils
                        .replace(returnFileName, " ", "%20");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return returnFileName;
    }

    /**
     * 判断操作系统类型
     *
     * @return
     */
    public static String getOsName() {
        String osName = System.getProperty("os.name");
        if (osName.contains("Mac")) {
            return "mac";
        } else if (osName.contains("Linux")) {
            return "linux";
        } else {
            return "win";
        }
    }

    /**
     * 简单排序类(冒泡）
     * 通过集合中的固有字段sort进行排序
     *
     * @param orderList 要排序的集合
     * @param sort      排序方式 desc asc
     */
    public static void sortList(List<Map<String, Object>> orderList, String sort) {
        int len = orderList.size();
        for (int i = 0; i < len; i++) {
            int selected = i;
            for (int j = i + 1; j < len; j++) {
                if (sort.equals("desc")) {
                    if (orderList.get(j).get("sort") != null
                            && !orderList.get(j).get("sort").toString().trim().equals("")
                            && orderList.get(selected).get("sort") != null
                            && !orderList.get(selected).get("sort").toString().trim().equals("")
                            && new BigDecimal(orderList.get(j).get("sort").toString()).compareTo(new BigDecimal(orderList.get(selected).get("sort").toString())) > 0) {
                        selected = j;
                    }
                    if (orderList.get(j).get("sort") != null
                            && !orderList.get(j).get("sort").toString().trim().equals("")
                            && orderList.get(selected).get("sort") == null) {
                        selected = j;
                    }
                } else {
                    if (orderList.get(j).get("sort") != null
                            && !orderList.get(j).get("sort").toString().trim().equals("")
                            && orderList.get(selected).get("sort") != null
                            && !orderList.get(selected).get("sort").toString().trim().equals("")
                            && new BigDecimal(orderList.get(j).get("sort").toString()).compareTo(new BigDecimal(orderList.get(selected).get("sort").toString())) < 0) {
                        selected = j;
                    }
                }
            }
            exchange(orderList, i, selected);
        }
    }

    /**
     * list元素互换（用于排序）
     *
     * @param list
     * @param a
     * @param b
     */
    public static void exchange(List list, int a, int b) {
        Object as = list.get(a);
        Object bs = list.get(b);
        list.set(a, bs);
        list.set(b, as);
    }

    /**
     * 将某个java bean转换为Map集合
     *
     * @param obj
     * @return
     */
    public static Map<String, Object> modelToMap(Object obj) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Field[] fields = obj.getClass().getDeclaredFields();
            for (Field f : fields) {
                f.setAccessible(true);
                map.put(f.getName(), f.get(obj));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 检测sql语句是否有注入风险
     *
     * @param sql
     * @return
     * @throws Exception
     */
    public static String checkSql(String sql) throws Exception {
        if (StringUtils.isBlank(sql) || sql.contains(";") || sql.contains("--")) {
            throw new Exception("不是有效的sql语句!或sql非法,存在sql注入风险!请检查语句!", null);
        } else {
            return sql;
        }
    }

    /**
     * 替换空对象为默认内容
     *
     * @param resource
     * @param result
     * @return
     */
    public static String Nvl(Object resource, String result) {
        if (resource != null && !resource.equals("")) {
            return resource.toString();
        } else {
            return result;
        }
    }

    /**
     * 得到访问地址(完整)
     *
     * @param request
     * @return
     */
    public static String getRequestUrl(HttpServletRequest request) {
        String uri = null;
        if (request != null) {
            Map<String, String[]> params = request.getParameterMap();
            String queryString = StringUtils.isBlank(request.getQueryString()) ? "" : request.getQueryString();
            for (String key : params.keySet()) {
                if (queryString.contains("&" + key) || queryString.contains("?" + key)) {
                } else {
                    String[] values = params.get(key);
                    for (int i = 0; i < values.length; i++) {
                        String value = values[i];
                        if (StringUtils.isBlank(queryString)) {
                            queryString += key + "=" + value + "&";
                        } else {
                            queryString += "&" + key + "=" + value + "&";
                        }
                    }
                }
            }
            if (queryString.length() > 1)
                queryString = queryString.substring(0, queryString.length() - 1);
            //得到服务器访问路径
            String saveQueryString = request.getScheme() + "://" + request.getServerName() + request.getServletPath().split("\\?")[0];
            //得到完整访问路径和参数
            String lastQueryUrl = saveQueryString + "?" + queryString;
            return lastQueryUrl;
        }
        return uri;
    }

    /**
     * 得到访问地址和访问数据。分开显示
     *
     * @param request
     * @return
     */
    public static Map<String, String> getRequestURI(HttpServletRequest request) {
        Map<String, String> requestData = new HashMap<>();
        if (request != null) {
            //得到服务器访问路径
            String uri = request.getScheme() + "://" + request.getServerName() + request.getServletPath().split("\\?")[0];
            requestData.put("uri", uri);
            //获取请求数据
            Map<String, String[]> params = request.getParameterMap();
            String queryString = StringUtils.isBlank(request.getQueryString()) ? "" : request.getQueryString();
            for (String key : params.keySet()) {
                if (queryString.contains("&" + key) || queryString.contains("?" + key)) {
                } else {
                    String[] values = params.get(key);
                    for (int i = 0; i < values.length; i++) {
                        String value = values[i];
                        if (StringUtils.isBlank(queryString)) {
                            queryString += key + "=" + value + "&";
                        } else {
                            queryString += "&" + key + "=" + value + "&";
                        }
                    }
                }
            }
            if (queryString.length() > 1) {
                queryString = queryString.substring(0, queryString.length() - 1);
            }
            requestData.put("data", queryString);
        }
        //返回结果
        return requestData;
    }

    /**
     * 验证用户是否拥有某个地址的访问权限
     *
     * @param requestUrl 用户访问地址
     * @param purviewUrl 系统权限资源地址
     * @return
     */
    public static boolean checkHasPreview(String requestUrl, String purviewUrl) {
        boolean reval = false;
        purviewUrl = purviewUrl.replace("?", "\\?").replace(".", "\\.");
        Pattern urlFilter = Pattern.compile(purviewUrl + "$|/" + purviewUrl + "$|" + purviewUrl + "/|/" + purviewUrl + "/|"
                + purviewUrl + "\\?|/" + purviewUrl + "\\?|" + purviewUrl + "&|/" + purviewUrl + "&");
        if (urlFilter.matcher(requestUrl).find()) {
            reval = true;
        }
        return reval;
    }

    /**
     * 将unicode字符转换为中文
     *
     * @param ori
     * @return
     */
    public static String convertUnicode(String ori) {
        char aChar;
        int len = ori.length();
        StringBuffer outBuffer = new StringBuffer(len);
        for (int x = 0; x < len; ) {
            aChar = ori.charAt(x++);
            if (aChar == '\\') {
                aChar = ori.charAt(x++);
                if (aChar == 'u') {
                    // Read the xxxx
                    int value = 0;
                    for (int i = 0; i < 4; i++) {
                        aChar = ori.charAt(x++);
                        switch (aChar) {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                value = (value << 4) + aChar - '0';
                                break;
                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                value = (value << 4) + 10 + aChar - 'a';
                                break;
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                value = (value << 4) + 10 + aChar - 'A';
                                break;
                            default:
                                throw new IllegalArgumentException(
                                        "Malformed   \\uxxxx   encoding.");
                        }
                    }
                    outBuffer.append((char) value);
                } else {
                    if (aChar == 't')
                        aChar = '\t';
                    else if (aChar == 'r')
                        aChar = '\r';
                    else if (aChar == 'n')
                        aChar = '\n';
                    else if (aChar == 'f')
                        aChar = '\f';
                    outBuffer.append(aChar);
                }
            } else
                outBuffer.append(aChar);

        }
        return outBuffer.toString();
    }

    /**
     * 取26个英文字母中某个顺序中的字母
     *
     * @param index 26个英文字母顺序索引
     * @return
     */
    public static String getLetterByIndex(int index) {
        List<String> letterList = new LinkedList<>();
        letterList.add("A");
        letterList.add("B");
        letterList.add("C");
        letterList.add("D");
        letterList.add("E");
        letterList.add("F");
        letterList.add("G");
        letterList.add("H");
        letterList.add("I");
        letterList.add("J");
        letterList.add("K");
        letterList.add("L");
        letterList.add("M");
        letterList.add("N");
        letterList.add("O");
        letterList.add("P");
        letterList.add("Q");
        letterList.add("R");
        letterList.add("S");
        letterList.add("T");
        letterList.add("U");
        letterList.add("V");
        letterList.add("W");
        letterList.add("X");
        letterList.add("Y");
        letterList.add("Z");
        return letterList.get(index);
    }

    /**
     * 取两数百分比
     *
     * @param p1
     * @param p2
     * @return
     */
    public static String percent(double p1, double p2) {
        String str;
        if (p2 != 0d) {
            double p3 = p1 / p2;
            NumberFormat nf = NumberFormat.getPercentInstance();
            nf.setMinimumFractionDigits(1);
            str = nf.format(p3);
        } else {
            str = "0";
        }
        return str;
    }

    /**
     * 产品属性拼接
     *
     * @param material 材质
     * @param style    风格
     * @return
     */
    public static String appendProInfo(Object material, Object style) {
        String proInfo = "";
        if (StringUtils.isNotBlank(CustomUtils.Nvl(material, " "))) {
            proInfo = material.toString();
        }
        if (StringUtils.isNotBlank(CustomUtils.Nvl(style, " "))) {
            proInfo += "," + style.toString();
        }
        return proInfo;
    }

    /**
     * 提供精确的除法运算方法div
     *
     * @param value1 被除数
     * @param value2 除数
     * @param scale  精确范围
     * @return 两个参数的商
     * @throws IllegalAccessException
     */
    public static double div(double value1, double value2, int scale) throws IllegalAccessException {
        //如果精确范围小于0，抛出异常信息
        if (scale < 0) {
            throw new IllegalAccessException("精确度不能小于0");
        }
        BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
        BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_EVEN).doubleValue();
    }

    /**
     * 提供精确的乘法运算。
     *
     * @param v1 被乘数
     * @param v2 乘数
     * @return 两个参数的积
     */
    public static Double mul(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.multiply(b2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 手机区号和手机号合并
     *
     * @param phone
     * @param areaCode
     * @return
     */
    public static String phoneAndAreaCode(String phone, String areaCode) {
        if (StringUtils.isNotBlank(phone) && StringUtils.isNotBlank(areaCode)) {
            phone = "00" + areaCode + phone;
        }
        return phone;
    }

    /**
     * 验证是否是图片
     *
     * @param str
     * @return
     */
    public static boolean isImage(String str) {
        boolean isOK = false;
        if (StringUtils.isNotBlank(str) && str.toUpperCase().contains("HTTP") && (str.contains("thirdwx.qlogo.cn") || str.toUpperCase().lastIndexOf(".PNG") > 1 || str.toUpperCase().lastIndexOf(".JPG") > 1 || str.toUpperCase().lastIndexOf("/SCALE") > 1)) {
            isOK = true;
        }
        return isOK;
    }

    /**
     * Created on 2014年4月27日
     * <p>
     * Discription:笛卡尔乘积算法
     * 把一个List{[1,2],[3,4],[a,b]}转化成List{[1,3,a],[1,3,b],[1,4
     * ,a],[1,4,b],[2,3,a],[2,3,b],[2,4,a],[2,4,b]}数组输出
     * </p>
     *
     * @param dimvalue 原List
     * @param result   通过乘积转化后的数组
     * @param layer    中间参数
     * @param curList  中间参数
     */
    private static void descartes(List<List<String>> dimvalue,
                                  List<List<String>> result, int layer, List<String> curList) {
        if (layer < dimvalue.size() - 1) {
            if (dimvalue.get(layer).size() == 0) {
                descartes(dimvalue, result, layer + 1, curList);
            } else {
                for (int i = 0; i < dimvalue.get(layer).size(); i++) {
                    List<String> list = new ArrayList<String>(curList);
                    list.add(dimvalue.get(layer).get(i));
                    descartes(dimvalue, result, layer + 1, list);
                }
            }
        } else if (layer == dimvalue.size() - 1) {
            if (dimvalue.get(layer).size() == 0) {
                result.add(curList);
            } else {
                for (int i = 0; i < dimvalue.get(layer).size(); i++) {
                    List<String> list = new ArrayList<String>(curList);
                    list.add(dimvalue.get(layer).get(i));
                    result.add(list);
                }
            }
        }
    }

    /**
     * 判断当前用户今天是否是生日，如果是生日则显示生日福利促销
     *
     * @param birthdayInfo 日期字符串
     * @return
     * @throws ParseException
     */
    public static boolean isBirthday(String birthdayInfo) throws ParseException {
        boolean birthdayFlag = false;
        SimpleDateFormat simpleDateFormat;
        Date date;
        try {
            if (StringUtils.isNotBlank(birthdayInfo)) {
                if (birthdayInfo.length() < 12) {
                    if (birthdayInfo.contains("-")) {
                        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        date = simpleDateFormat.parse(birthdayInfo);
                        Calendar now = Calendar.getInstance();
                        Calendar cale = Calendar.getInstance();
                        cale.setTime(date);
                        int month = cale.get(Calendar.MONTH) + 1;
                        int day = cale.get(Calendar.DATE);
                        if (month == (now.get(Calendar.MONTH) + 1) && day == now.get(Calendar.DATE)) {
                            birthdayFlag = true;
                        }
                    }
                }
            }
        } catch (ParseException e) {
            birthdayFlag = false;
        }
        return birthdayFlag;
    }

    /**
     * 手机号验证
     *
     * @param str
     * @return 验证通过返回true
     */
    public static boolean isMobile(final String str) {
        Pattern p = null;
        Matcher m = null;
        boolean b = false;
        p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
        m = p.matcher(str);
        b = m.matches();
        return b;
    }

    /**
     * 座机电话号码验证
     *
     * @param str
     * @return 验证通过返回true
     */
    public static boolean isPhone(final String str) {
        Pattern p1 = null, p2 = null;
        Matcher m = null;
        boolean b = false;
        p1 = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$"); // 验证带区号的
        p2 = Pattern.compile("^[1-9]{1}[0-9]{5,8}$");     // 验证没有区号的
        if (str.length() > 9) {
            m = p1.matcher(str);
            b = m.matches();
        } else {
            m = p2.matcher(str);
            b = m.matches();
        }
        return b;
    }


    /**
     * 验证是否是自然数，0和正整数
     *
     * @param string
     * @return
     */
    public static boolean isNumber(final String string) {
        Pattern pattern = Pattern.compile("^\\d+$");
        Matcher matcher = pattern.matcher(string);
        return matcher.matches();
    }

    /**
     * 将UTC时间转换为本地时间
     *
     * @param utcDataStr UTC时间字符串，格式：2018-08-07T01:00:59.000Z
     * @return
     */
    public static Date UTCToLocalTime(String utcDataStr) throws ParseException {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        SimpleDateFormat sfl = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSS'Z'");
        TimeZone utcZone = TimeZone.getTimeZone("UTC");
        sf.setTimeZone(utcZone);
        Date date;
        try {
            date = sf.parse(utcDataStr);
        } catch (Exception ex) {
            date = sfl.parse(utcDataStr);
        }
        return date;
    }


    /**
     * 获取某一段时间内所以的日期
     *
     * @param dBegin
     * @param dEnd
     * @return
     */
    public static List<Date> findDates(Date dBegin, Date dEnd) {
        List lDate = new ArrayList();
        lDate.add(dBegin);
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            lDate.add(calBegin.getTime());
        }
        return lDate;
    }


    /**
     * 加密昵称
     * 昵称为1位：*
     * 昵称为2位，隐藏后一位：某*
     * 昵称为3位，隐藏中间一位：某*某
     * 昵称为4位，隐藏中间二位：某**某
     * 昵称为5位，隐藏第三四位：某某**某
     * 昵称为6位，隐藏第三四位：某某**某某
     * 昵称为7位及以上，只显示前二位和后二位 ：某某***某某
     *
     * @param nickname
     * @return
     */
    public static String encryptionNickname(String nickname) {
        String fxl = "*";
        if (StringUtils.isNotBlank(nickname)) {
            String result = "";
            int len = nickname.length();
            if (len > 1) {
                if (len == 2) {
                    result = nickname.substring(0, 1) + "*";
                } else if (len == 3) {
                    result = nickname.substring(0, 1) + "*" + nickname.substring(2, 3);
                } else if (len == 4) {
                    result = nickname.substring(0, 1) + "**" + nickname.substring(3, 4);
                } else if (len == 5) {
                    result = nickname.substring(0, 2) + "**" + nickname.substring(4, 5);
                } else {
                    StringBuilder sb = new StringBuilder(nickname);
                    int i1 = len - 4;
                    for (int i = 0; i < i1; i++) {
                        fxl += "*";
                    }
                    result = sb.replace(2, len - 2, fxl).toString();
                }
                return result;
            } else {
                return fxl;
            }
        } else {
            return "";
        }
    }


    /**
     * 取客户端访问的IP地址
     *
     * @param request
     * @return
     */
    public static String getClientIp(HttpServletRequest request) {
        //得到访问IP
        String internetProtocol = request.getHeader("x-forwarded-for");//访问IP
        if (internetProtocol == null || internetProtocol.length() == 0 || "unknow".equalsIgnoreCase(internetProtocol)) {
            internetProtocol = request.getHeader("Proxy-Client-IP");
        }
        if (internetProtocol == null || internetProtocol.length() == 0 || "unknow".equalsIgnoreCase(internetProtocol)) {
            internetProtocol = request.getHeader("WL-Proxy-Client-IP");
        }
        if (internetProtocol == null || internetProtocol.length() == 0 || "unknow".equalsIgnoreCase(internetProtocol)) {
            internetProtocol = request.getRemoteAddr();
        }
        return StringUtils.isBlank(internetProtocol) ? "" : internetProtocol.split(",")[0];
    }

    /**
     * Map.toString 的字符串转Map
     *
     * @param str
     */
    public static Map<String, String> mapStringToMap(String str) {
        str = str.substring(1, str.length() - 1);
        String[] strs = str.split(",");
        Map<String, String> map = new HashMap<String, String>();
        for (String string : strs) {
            String key = string.split("=")[0].trim();
            String value = string.split("=")[1].trim();
            map.put(key, value);
        }
        return map;
    }

    public Map<String, Object> listToMap(List<Map<String, Object>> list, String key) {
        Map<String, Object> map = new HashMap<>();
        for (Map<String, Object> obj : list) {
            map.put(key, obj.get(key));
        }
        return map;
    }
}
